import { IHttpResponse, IObject } from "@/types/interface";
import app from '@/constants/app';
import axios, { AxiosRequestConfig } from "axios";
import { getToken } from "./cache";
import qs from "qs";
import router from "@/router";
import { getValueByKeys } from "./utils";

// 创建axios实例
const service = axios.create({
    //服务接口请求
    baseURL: import.meta.env.VITE_APP_BASE_API,
    // 超时设置
    timeout: app.requestTimeout,
    headers:{'Content-Type':'application/json;charset=utf-8'}
});

service.interceptors.request.use(
    function (config:any){
      config.headers['X-Requested-With'] = 'XMLserviceRequest';
      // const token = getToken();
      const token = "83845ef534684046813dfe2d7c86f1a1";
      if (token) {
          config.headers["token"] = token;
      }
      
      if (Object.values(config.headers).includes("application/x-www-form-urlencoded")) {
          config.data = qs.stringify(config.data);
      }

      return config;
    },
    function (error) {
        return Promise.reject(error);
    }
)

service.interceptors.response.use(
    (response) => {
      if (response.data.code === 401) {
        //自定义业务状态码
        redirectLogin();
      }
      return response;
    },
    (error) => {
      const status = getValueByKeys(error, "response.status", 500);
      const serviceCodeLabel: IObject<string> = {
        400: "请求参数错误",
        401: "未授权，请登录",
        403: "拒绝访问",
        404: `请求地址出错: ${getValueByKeys(error, "response.config.url", "")}`,
        408: "请求超时",
        500: "API接口报500错误",
        501: "服务未实现",
        502: "网关错误",
        503: "服务不可用",
        504: "网关超时",
        505: "service版本不受支持"
      };
      if (error && error.response) {
        console.error("请求错误", error.response.data);
      }
      if (status === 401) {
        redirectLogin();
      }
      return Promise.reject(new Error(serviceCodeLabel[status] || "接口错误"));
    }
  );
  
  const redirectLogin = () => {
    router.replace("/login");
    return;
  };

export default (o: AxiosRequestConfig): Promise<IHttpResponse> => {
    return new Promise((resolve, reject) => {
      service(o)
        .then((res) => {
          return resolve(res.data);
        })
        .catch(reject);
    });
  };